package com.gitee.chessboard.db.impl;

import com.gitee.chessboard.db.DictionaryService;
import com.gitee.chessboard.db.MybatisService;
import com.gitee.chessboard.jdbc.JdbcManager;
import com.gitee.chessboard.manager.DefaultDictionaryManager;
import com.gitee.chessboard.manager.DictionaryManager;
import com.gitee.chessboard.parser.DefaultConstantDictionaryParser;
import com.gitee.chessboard.parser.DefaultEnumDictionaryParser;
import com.intellij.openapi.components.ServiceManager;
import com.intellij.openapi.project.Project;
import org.apache.ibatis.datasource.pooled.PooledDataSource;
import org.apache.ibatis.session.Configuration;
import org.apache.ibatis.session.SqlSessionFactory;

/**
 * @author 敲代码的旺财
 * @date 2021/12/23 13:16
 */
public class DictionaryServiceImpl implements DictionaryService {

    private DictionaryManager dictionaryManager;

    public DictionaryServiceImpl(Project project) {
        MybatisService mybatisService = ServiceManager.getService(project, MybatisService.class);
        SqlSessionFactory sqlSessionFactory = mybatisService.getSqlSessionFactory();
        Configuration configuration = sqlSessionFactory.getConfiguration();
        PooledDataSource dataSource = (PooledDataSource) configuration.getEnvironment().getDataSource();
        JdbcManager jdbcManager = new JdbcManager(
                dataSource.getDriver()
                , dataSource.getUrl()
                , dataSource.getUsername()
                , dataSource.getPassword());
        jdbcManager.setMybatisSqlSessionFactory(sqlSessionFactory);
        DefaultDictionaryManager manager = new DefaultDictionaryManager(jdbcManager);
        manager.setEnumDictionaryParser(new DefaultEnumDictionaryParser(manager));
        manager.setConstantDictionaryParser(new DefaultConstantDictionaryParser(manager));
        manager.init();
        this.dictionaryManager = manager;
    }

    public DictionaryManager getDictionaryManager() {
        return dictionaryManager;
    }

}
